package ch.il07.converter.persistance.tests;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

import org.junit.Before;
import org.junit.Test;

import ch.il07.converter.persistence.Persistence;
import ch.il07.converter.persistence.PersistenceHelper;
import ch.il07.converter.persistence.entities.AccessLevel;
import ch.il07.converter.persistence.exceptions.PersistenceException;
import ch.il07.converter.persistence.exceptions.UserAlreadyExistsException;
import ch.il07.utils.RandomHelper;

public class LoginTest {

	private Persistence persistence;

	@Before
	public void setUp() {
		try {
			persistence = PersistenceHelper.getPersistence();
		} catch (PersistenceException e) {
			fail(e.getMessage());
		}
	}

	@Test
	public void loginOk() {
		String username = RandomHelper.randString();
		try {
			persistence.addUser(username, RandomHelper.getEmail(username), username,
					AccessLevel.USER);
			assertNotNull("user '" + username + "' should exist in db", persistence
					.getUser(username, username));
		} catch (UserAlreadyExistsException e) {
			fail(e.getMessage());
		} catch (PersistenceException e) {
			fail(e.getMessage());
		}

	}

	@Test
	public void loginNotOk() {
		String username = RandomHelper.randString();
		try {
			assertNull("user '"+username+"' should not exist", persistence.getUser(
					username, username));
		} catch (UserAlreadyExistsException e) {
			fail(e.getMessage());
		} catch (PersistenceException e) {
			fail(e.getMessage());
		}
	}

	@Test
	public void loginWithFalsePassword() {
		String username = RandomHelper.randString();
		try {
			persistence.addUser(username, RandomHelper.getEmail(username), username,
					AccessLevel.USER);
			assertNull("should return null for a wrong password", persistence.getUser(
					username, RandomHelper.randString()));
		} catch (UserAlreadyExistsException e) {
			fail(e.getMessage());
		} catch (PersistenceException e) {
			fail(e.getMessage());
		}
	}
}